package com.SXJ.web;

import com.SXJ.pojo.User;
import com.SXJ.service.UserService;
import com.SXJ.service.impl.UserServiceImpl;
import com.SXJ.utils.WebUtils;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

//@WebServlet(name = "UserServlet")
public class UserServlet extends BaseServlet {
    private UserService userService = new UserServiceImpl();

    protected void ajaxExistsUsername(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取请求的参数username
        String username = req.getParameter("username");
        // 调用userService.existsUsername();
        boolean existsUsername = userService.existsUsername(username);
        // 把返回的结果封装成为map对象
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("existsUsername",existsUsername);

        Gson gson = new Gson();
        String json = gson.toJson(resultMap);

        resp.getWriter().write(json);
    }

    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        1、销毁Session中用户登录的信息（或者销毁Session）
        req.getSession().invalidate();
//        2、重定向到首页（或登录页面）。
        resp.sendRedirect(req.getContextPath());
    }

    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //1. 获取请求的参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        //2. 调用xxxService.xxx() 处理业务
        //userService.login()登录
        User loginUser = userService.login(new User(null, username, password, null));

        //3.根据login方法返回结果判断登录是否成功
        if(loginUser == null){
            //不成功，跳回登录页面

            req.setAttribute("msg" , "用户名或密码错误");
            req.setAttribute("username" , username);
            req.getRequestDispatcher("/pages/user/login.jsp").forward(req , resp);
        }else{
            //登录，成功
            //保存用户登录的信息到Session域中
            req.getSession().setAttribute("user", loginUser);

            //成功，就跳到login_success.html 页面

            req.getRequestDispatcher("/pages/user/login_success.jsp").forward(req , resp);
        }
}
    protected void regist(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取Session中的验证码
        String token = (String) req.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        // 删除 Session中的验证码
        req.getSession().removeAttribute(KAPTCHA_SESSION_KEY);

        //  1、获取请求的参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        String code = req.getParameter("code");

        User user = WebUtils.copyParamToBean(req.getParameterMap(), new User());

//        2、检查 验证码是否正确  === 写死,要求验证码为:abcde
        if (token!=null && token.equalsIgnoreCase(code)) {
            //检查用户名是否可用
            if(userService.existsUsername(username)){
                //不可用 ，跳回注册页面
                req.setAttribute("msg" , "用户名已存在");
                req.setAttribute("username" , username);
                req.setAttribute("email" , email);

                req.getRequestDispatcher("/pages/user/regist.jsp").forward(req , resp);

            }else{
                //调用 service 保存到数据库
                userService.registUser(new User(null , username , password , email));
                //跳到注册成功页面
                req.getRequestDispatcher("/pages/user/regist_success.jsp").forward(req , resp);
            }
        }else{
            //不正确，跳回注册页面
            //把回显信息，保存到request 域中
            req.setAttribute("msg" , "验证码错误");
            req.setAttribute("username" , username);
            req.setAttribute("email" , email);

            System.out.println("验证码[" + code + "]错误");
            req.getRequestDispatcher("/pages/user/regist.jsp").forward(req , resp);
        }

    }


//    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        String action = request.getParameter("action");
//        if("login".equals(action)){
//            login(request,response);
//        }if("regist".equals(action)){
//            regist(request,response);
//        }
//    }

    /*protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action = request.getParameter("action");

        try {
            Method method = this.getClass().getDeclaredMethod(action , HttpServletRequest.class , HttpServletResponse.class);
            method.invoke(this , request , response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }*/

}
